package com.chart.web.controller.system;

import cn.hutool.core.date.LocalDateTimeUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.chart.common.constant.Constants;
import com.chart.common.core.domain.AjaxResult;
import com.chart.common.core.domain.entity.SysDemand;
import com.chart.common.core.domain.entity.SysMenu;
import com.chart.common.core.domain.entity.SysUser;
import com.chart.common.core.domain.entity.SysWhiteUser;
import com.chart.common.core.domain.model.LoginBody;
import com.chart.common.utils.SecurityUtils;
import com.chart.framework.web.service.SysLoginService;
import com.chart.framework.web.service.SysPermissionService;
import com.chart.system.domain.SysUserOrder;
import com.chart.system.mapper.SysUserMapper;
import com.chart.system.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Set;

/**
 * 登录验证
 *
 * @author chart
 */
@Api(tags = "登陆模块")
@RestController
public class SysLoginController {
    @Autowired
    private SysLoginService loginService;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private ISysUserDemandService userDemandService;


    @Autowired
    private ISysUserOrderService userOrderService;

    @Autowired
    private IUserCoinLogsService userCoinLogsService;

    @Autowired
    private ISysUserService userService;


    @Autowired
    private SysWhiteUserService SysWhiteUserService;

    @Resource
    private SysUserMapper userMapper;


    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @ApiOperation("登录方法")
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody, HttpServletRequest request) {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword());
        ajax.put(Constants.TOKEN, token);
        // 更新登录信息
        SysUser sysUser = userService.selectUserByUserName(loginBody.getUsername());
        Long userId = sysUser.getUserId();
        String loginIp = request.getRemoteAddr(); // 获取登录IP
        userService.updateLoginCountAndHistory(userId, loginIp);


        return ajax;
    }

    /**
     * 管理后台登录接口
     *
     * @param loginBody
     * @param request
     * @return
     */

    @ApiOperation("登录方法")
    @PostMapping("/login/management")
    public AjaxResult loginManagement(@RequestBody LoginBody loginBody, HttpServletRequest request) {

        String username = loginBody.getUsername();
        if (username == null) {
            return AjaxResult.error("用户名是空");
        }
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getUserName, username);
        SysUser user = userService.selectUserByUserName(username);
        if (user == null) {
            return AjaxResult.error("用户不存在");
        }
        String phonenumber = user.getPhonenumber();
        if (phonenumber == null) {
            return AjaxResult.error("未查询到该用户的手机号");
        }
        LambdaQueryWrapper<SysWhiteUser> lqw = new LambdaQueryWrapper<>();
        lqw.eq(SysWhiteUser::getPhonenumber, phonenumber);
        List<SysWhiteUser> list = SysWhiteUserService.list(lqw);
        if(!list.isEmpty()){
            AjaxResult ajax = AjaxResult.success();
            // 生成令牌
            String token = loginService.login(loginBody.getUsername(), loginBody.getPassword());
            ajax.put(Constants.TOKEN, token);
            // 更新登录信息
            SysUser sysUser = userService.selectUserByUserName(loginBody.getUsername());
            Long userId = sysUser.getUserId();
            String loginIp = request.getRemoteAddr(); // 获取登录IP
            userService.updateLoginCountAndHistory(userId, loginIp);
            return ajax;
                }
        return AjaxResult.error("未配置白名单");
    }


    @GetMapping("text")
    public AjaxResult getUserInfo() {

        List<SysUser> list = userService.list();
        Long userId = SecurityUtils.getUserId();
        SysUser sysUser = userService.queryById(userId);

        return AjaxResult.success(sysUser);
    }

    /**
     * 判断用户是否关注公众号
     *
     * @return
     */
    @GetMapping("textS")
    public AjaxResult textS() {

        Long userId = SecurityUtils.getUserId();
        SysUser sysUser = userService.queryById(userId);

        String openId = sysUser.getOpenId();


        // AppID（应用ID） 和 AppSecret（应用密钥）。
        https:
//api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx1e73641cc7528a1c&secret=01aece16ec2576524da629ef3d52dace


        // https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET


        return AjaxResult.success(sysUser);
    }


    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @ApiOperation("获取用户信息")
    @GetMapping("getInfo")
    public AjaxResult getInfo() {
        // 之前的获取用户信息
        // SysUser user = SecurityUtils.getLoginUser().getUser();

        //现在的
        Long userId = SecurityUtils.getUserId();
        SysUser user = userService.queryById(userId);

        List<SysDemand> demands = userDemandService.getDemandList(user.getUserId());
        user.setDemands(demands);
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        // Set<String> permissions = permissionService.getMenuPermission(user);


        SysUserOrder order = userOrderService.getOne(new LambdaQueryWrapper<SysUserOrder>().eq(SysUserOrder::getUserId, user.getUserId()));

        if (order != null) {
            if (order.getExpirationTime().isBefore(LocalDateTimeUtil.now())) {
                user.setIsVip(0);
                userMapper.updateById(user);
            } else {
                user.setExpirationTime(order.getExpirationTime());
            }
        }
        Integer totalCoins = userCoinLogsService.getTotalCoinsByUserId(user.getUserId());
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("totalCoins", totalCoins);

        return ajax;
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @ApiOperation("获取路由信息")
    @GetMapping("getRouters")
    public AjaxResult getRouters() {
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        return AjaxResult.success(menuService.buildMenus(menus));
    }

}
